package tgc.edu.exam.custom;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.exam.custom.dict.entity.TbClassState;
import tgc.edu.exam.custom.dict.service.TbClassStateService;
import tgc.edu.exam.entity.Checkingin;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysFile;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.service.CheckinginService;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.SysFileService;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.web.form.CheckinginForm;

@Component
@Configurable
@EnableScheduling
public class TimerTask {
	@Autowired
	private TbClassService tcService;
	@Autowired
	private TbClassStateService tsService;
	@Autowired
	private StudentService stuService;
	@Autowired
	private SysFileService fileservice;
	@Autowired
	private CheckinginService checkingService;

	@Scheduled(cron = "0 0 0 * * ?")
	public void test() throws ParseException {
		try {
			// 要执行的任务逻辑写在这里
			boolean b = deleteDirectory("d:/jeecgs");
			System.out.println(b);
			System.out.println("删除成功！");

			/**
			 * 修改班级状态
			 */
			List<TbClass> list = tcService.findAll();
			List<TbClass> tc = tcService.findByClassStatusStateNot("结业");
			SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
			String format = sdf.format(new Date());
			TbClassState ts = tsService.findByState("结业");
			TbClassState ts1 = tsService.findByState("开班");
			for (int i = 0; i < list.size(); i++) {
				TbClass tb = list.get(i);
				Date closetime = sdf.parse(tb.getCloseTime());
				if (!TimeUtils.AfterTime2(closetime)) {
					tb.setClassStatus(ts);
					tcService.save(tb);
				}
			}
			for (int i = 0; i < tc.size(); i++) {
				TbClass tb = list.get(i);
				Date closetime1 = sdf.parse(tb.getStartTime());
				if (!TimeUtils.AfterTime2(closetime1)) {
					tb.setClassStatus(ts1);
					tcService.save(tb);
				}
			}

			/**
			 * 修改毕业学生状态
			 */
			List<TbClass> tbClass = tcService.findByClassStatusId(ts.getId());
			String outPutPath = "c:\\jeecgs\\004.jpg";
			String backgroundPath = "c:\\jeecgs\\模版.png";

			for (int i = 0; i < tbClass.size(); i++) {
				TbClass tbClass1 = tbClass.get(i);
				List<Student> list1 = stuService.findByTbClassId(tbClass1.getId());
				String date = tbClass1.getCloseTime();
				Date date1 = TimeUtils.getPlusdays2(date, 15);
				if (!TimeUtils.AfterTime2(date1)) {
					for (int a = 0; a < list1.size(); a++) {
						String uuid = UUID.randomUUID().toString();
						Student stu = list1.get(a);
						stu.setUsername(uuid);
						stu.setOpenId("");
						stu.setType(null);
						stu.setIsUsed(false);
						stuService.save(stu);
					}
				} else {
					for (int a = 0; a < list1.size(); a++) {
						Student stu = list1.get(a);
						boolean ishao = ishao(stu);
						if (ishao) {
							if (!StringUtils.hasText(stu.getCertificateuuid())) {
								String uuid1 = UUID.randomUUID().toString();
								String[] split = tbClass1.getStartTime().split("-");
								String[] split2 = tbClass1.getCloseTime().split("-");
								String ksrq = split[0] + " 年 " + split[1] + " 月 " + split[2] + " 日";
								String jsrq = split2[0] + " 年 " + split2[1] + " 月 " + split2[2] + " 日";
								ImageeditUtils.overlapImage(backgroundPath, stu.getName(), ksrq, jsrq,
										tbClass1.getSubject(), outPutPath);
								File file = new File(outPutPath);
								FileInputStream fileInputStream = new FileInputStream(file);
								MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
										ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
								fileservice.savefile(multipartFile, uuid1);
								fileInputStream.close();
								if (file.exists() && file.isFile()) {
									file.delete();
								}
								stu.setCertificateuuid(uuid1);
								stuService.save(stu);
								SysFile sysFileEntity = fileservice.findByUuid(uuid1);
								sysFileEntity.setIsUsed(true);
								fileservice.save(sysFileEntity);

							}
						}
					}
				}
			}

		} catch (Exception e) {
			System.out.println("删除失败！");
		}

	}

	public boolean ishao(Student stu) {
		boolean ishao = false;
		Specification<Checkingin> spec = buildSpec(stu);
		Specification<Checkingin> spec1 = buildSpec1(stu);
		List<Checkingin> list = checkingService.findAll(spec);
		List<Checkingin> list2 = checkingService.findAll(spec1);
		Double kao = (double) (list.size() / list2.size());
		Double qing = (double) (6 / 7);
		if ((kao >= qing) && (stu.getPerformance() >= 60)) {
			ishao = true;
		}

		return ishao;

	}

	public Specification<Checkingin> buildSpec(Student stu) {
		Specification<Checkingin> spec = new Specification<Checkingin>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Checkingin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();

				rules.add(cb.equal(root.get("student").get("id"), stu.getId()));
				rules.add(cb.equal(root.get("isReach"), "正常"));

				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	public Specification<Checkingin> buildSpec1(Student stu) {
		Specification<Checkingin> spec = new Specification<Checkingin>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Checkingin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();

				rules.add(cb.equal(root.get("student").get("id"), stu.getId()));

				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param dir 被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator)) {
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			System.out.println("删除目录失败" + dir + "目录不存在！");
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			System.out.println("删除目录失败");
			return false;
		}

		// 删除当前目录
		if (dirFile.delete()) {
			System.out.println("删除目录" + dir + "成功！");
			return true;
		} else {
			System.out.println("删除目录" + dir + "失败！");
			return false;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param fileName 被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.isFile() && file.exists()) {
			file.delete();
			System.out.println("删除单个文件" + fileName + "成功！");
			return true;
		} else {
			System.out.println("删除单个文件" + fileName + "失败！");
			return false;
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	// 删除文件夹
	// param folderPath 文件夹完整绝对路径

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
